package top.cdmrx.www.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.cdmrx.www.demo.service.MsmService;

import java.util.Map;

/**
 * Created by Mr.陈 time on 2021/11/30 | 14:13
 **/
@Service
public class MsmServiceImpl implements MsmService {

    /**
     * 发送验证码
     * @param param 封装随机验证码
     * @param phone 手机号
     * @param templateCode 模板代码（阿里云申请的）
     * @return
     */
    @Override
    public boolean send(Map<String, Object> param, String phone, String templateCode) {
        if(StringUtils.isEmpty(phone)) return false;

        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI5tEcxd6NVo3516e1qDpv",
                        "QhQAJLCrNTm2Iy6JvxhnaMl2Y8TARn");
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //设置发送参数
        //手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //申请阿里云短信签名
        request.putQueryParameter("SignName", "MRX的虚幻空间");
        //申请阿里云短信模板
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam",
                JSONObject.toJSONString(param));

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
